<?php

namespace App\Http\Controllers;

use App\Models\Ad;
use App\Models\NoticeInfo;
use App\Models\TuanInfo;
use App\Models\UserComment;
use DB;
use Exception;
use Illuminate\Http\Request;

/**
 * 团购相关
 */
class TuanController extends Controller
{
    /**
     * 优惠专区（后台设置的3个团购）
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function discount_tuans(Request $request)
    {
        try {
            $status = 0;
            $data   = [];
            $cityID = $request->get('city_id');
            if (empty($cityID)) {
                throw new Exception('缺少参数！');
            }
            //优惠专区（后台设置的三个优惠团购）广告中查询
            $ads = Ad::where([
                'city_id' => $cityID, 'site_id' => 2, 'type' => 2, 'closed' => 1,
            ])->limit(3)->get();

            //处理数据
            foreach ($ads as $key => $value) {
                $data[$key]['tuan_id'] = $value->tuan_info->tuan_id;
                $data[$key]['title']   = $value->tuan_info->title;
                $data[$key]['photo']   = $value->photo;
            }

            $status = 1;
            $msg    = '查询成功';
        } catch (Exception $e) {
            $msg = $e->getMessage();
        }

        return response()->json(['status' => $status, 'msg' => $msg, 'data' => $data]);
    }

    /**
     * 猜你喜欢（三十条团购）
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function guess_likes(Request $request)
    {
        try {
            $status = 0;
            $data   = [];
            $cityID = $request->get('city_id');
            if (empty($cityID)) {
                throw new Exception('缺少参数！');
            }
            $page = $request->get('page');
            if($page == 4) {
                throw new Exception('最多30条');
            }
            //广告中团购id
            $ads = Ad::where(['site_id' => 4, 'city_id' => $cityID, 'closed' => 1])
                ->where('bg_date', '<', time())->where('end_date', '>', time())
                ->orderBy('orderby')
                ->pluck('goal')
                ->toArray();
            //团购id
            $ids = TuanInfo::where([
                'status' => 1, 'closed' => 1, 'audit' => 1, 'type' => 1, 'city_id' => $cityID,
            ])->where('bg_date', '<', time())->where('end_date', '>', time())
                ->orderBy('sold_num', 'desc')
                ->pluck('tuan_id')
                ->toArray();
            //合并数组并去重
            $tuanIds = array_unique(array_merge($ads, $ids));
            $qs      = array_fill(0, count($tuanIds), '?');
            //DB::connection()->enableQueryLog();
            $tuans = TuanInfo::whereIn('tuan_id', $tuanIds)
                ->orderByRaw(DB::raw("FIELD(tuan_id," . implode(',', $qs) . ")"), $tuanIds)->paginate(10);
            //dump(DB::getQueryLog());
            $status = 1;
            $msg    = '查询成功';
            //处理数据
            foreach ($tuans as $key => $value) {
                $data[$key]['tuan_id']    = $value->tuan_id;
                $data[$key]['title']      = $value->title;
                $data[$key]['intro']      = $value->intro;
                $data[$key]['photo']      = $value->photo;
                $data[$key]['price']      = sprintf('%.2f', $value->price / 100);
                $data[$key]['tuan_price'] = sprintf('%.2f', $value->tuan_price / 100);
                //$data[$key]['attr_value'] = $value->tuan->shop->shop_attr_value()->limit(2)->pluck('front_style');
                //获取评分信息
                $comments  = UserComment::where(['tuan_id' => $value->tuan_id, 'is_show' => 1, 'closed' => 1])->get();
                $score_num = $comments->count();
                $score     = $comments->avg('score');
                if ($score_num == 0) {
                    $score = 0;
                }
                $data[$key]['score'] = sprintf('%.1f', $score);
            }
        } catch (Exception $e) {
            $msg = $e->getMessage();
        }

        return response()->json(['status' => $status, 'msg' => $msg, 'data' => $data]);
    }

    /**
     * 团购详情
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function tuan_info(Request $request)
    {
        try {
            $status  = 0;
            $data    = [];
            $tuan_id = $request->get('tuan_id');
            if (empty($tuan_id)) {
                throw new Exception('缺少参数');
            }
            //团购信息
            $tuan                    = TuanInfo::where('tuan_id', $tuan_id)->first();
            $tuan_info               = [];
            $tuan_info['tuan_id']    = $tuan->tuan_id;
            $tuan_info['title']      = $tuan->title; //团购名称
            $tuan_info['intro']      = $tuan->intro; //介绍
            $tuan_info['photo']      = $tuan->photo; //图片
            $tuan_info['price']      = sprintf('%.2f', $tuan->price / 100); //门市价
            $tuan_info['tuan_price'] = sprintf('%.2f', $tuan->tuan_price / 100); //门市价
            $tuan_info['sold_num']   = $tuan->sold_num; //销量

            //商家信息
            $shop                   = $tuan->tuan->shop;
            $shop_info              = [];
            $shop_info['shop_name'] = $shop->shop_name;
            $shop_info['addr']      = $shop->addr;
            $shop_info['tel']       = $shop->tel;

            $data['tuan_info'] = $tuan_info;
            $data['shop_info'] = $shop_info;
            $status            = 1;
            $msg               = '查询成功';
        } catch (Exception $e) {
            $msg = $e->getMessage();
        }

        return response()->json(['status' => $status, 'msg' => $msg, 'data' => $data]);
    }

    /**
     * 图文详情
     * @param  Request $request [description]
     * @return [type]           [description]
     */
    public function image_and_text(Request $request)
    {
        try {
            $status  = 0;
            $data    = [];
            $tuan_id = $request->get('tuan_id');
            if (empty($tuan_id)) {
                throw new Exception('缺少参数');
            }
            //团购信息
            $tuan                       = TuanInfo::where('tuan_id', $tuan_id)->first();
            $tuan_info['price']         = sprintf('%.2f', $tuan->price / 100); //门市价
            $tuan_info['tuan_price']    = sprintf('%.2f', $tuan->tuan_price / 100); //门市价
            $tuan_info['description']   = $tuan->description;
            $tuan_info['term_validity'] = $this->check_tuan_info($tuan);
            $tuan_info['use_time']      = $tuan->bg_available_date . '至' . $tuan->end_available_date;
            //团购须知
            $notices   = $tuan->tuan_notices->pluck('notice_info_id')->toArray();
            $infos     = NoticeInfo::whereIn('id', $notices)->orderBy('order', 'desc')->pluck('front_show')->toArray();
            $shop_tags = $tuan->tuan->shop->shop_attr_value()->pluck('front_style')->toArray();

            $tuan_info['tuan_notices'] = array_merge($infos, $shop_tags);
            //套餐详情
            $combos = $tuan->combos;
            $arr    = [];
            foreach ($combos as $k => $v) {
                $arr[$k]['name'] = $v->name; //套餐名
                $combo_infos     = [];
                foreach ($v->combo_info as $key => $value) {
                    $combo_infos[$key]['name']  = $value->name;
                    $combo_infos[$key]['price'] = sprintf('%.2f', $value->price / 100);
                    $combo_infos[$key]['unit']  = $value->num . $value->unit;
                }
                $arr[$k]['infos'] = $combo_infos;
            }
            $tuan_info['combos'] = $arr;

            $imgs = $tuan->tuan_imgs;
            //处理图片
            $imgArr = [];
            foreach ($imgs as $kk => $vv) {
                $imgArr[$kk]['img_url'] = $vv->img_url;
            }
            //商家介绍
            $tuan_info['tuan_imgs'] = $imgArr;

            $status = 1;
            $msg    = '查询成功';
            $data   = $tuan_info;
        } catch (Exception $e) {
            $msg = $e->getMessage();
        }

        return response()->json(['status' => $status, 'msg' => $msg, 'data' => $data]);
    }

    //处理团购信息
    private function check_tuan_info($tuan)
    {
        //日期
        if ($tuan->type == 1) {
            $dateStr = date('Y.m.d', $tuan->bg_date) . '至' . date('Y.m.d', $tuan->end_date);
        } else {
            $dateStr = date('Y.m.d', $tuan->bg_coupon_date) . '至' . date('Y.m.d', $tuan->end_coupon_date);

        }
        //可用的日期区间
        if ($tuan->is_day_off == 0) {
            $str1 = '法定假日通用';
        } else {
            $str1 = '法定假日不可用';
        }

        if ($tuan->is_week == 0) {
            $str2 = '周末通用';
        } else {
            $str2 = '周末不可用';
        }

        return $dateStr . '(' . $str1 . '，' . $str2 . ')';
    }
}
